<?php

namespace App\Http\Controllers;


use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;


class UserController extends Controller
{
    public function saveUser(Request $request){
        $name = $request->input('name','');
        $image = $request->input('image','');
        $openid = $request->input('openid','');
        if (empty($name) || empty($image) || empty($openid)){
            if (empty($category_id)){
                return response()->json(['code'=>10003,'msg'=>'参数不全']);
            }
        }
        $user = DB::table('users')->where('openid',$openid)->first();
        $user =  objectToArray($user);
        if (empty($user)){
            $data = [
                'name'=>$name,
                'image'=>$image,
                'openid'=>$openid,
                'created_at'=>date('Y-m-d H:i:s',time()),
                'updated_at'=>date('Y-m-d H:i:s',time()),
            ];
            $res = DB::table('users')->insertGetId($data);
            $data['id'] = $res;
        }else{
            $data = [
                'name'=>$name,
                'image'=>$image,
                'updated_at'=>date('Y-m-d H:i:s',time()),
            ];
            $res = DB::table('users')->where('openid',$openid)->update($data);
            $data['id'] = $user['id'];
            $data['openid'] = $user['openid'];
        }

        return response()->json(['code'=>0,'data'=>$data]);

    }

    public function getUser(Request $request){
        $user_id = $request->input('user_id',0);
        $user = DB::table('users')->where('id',$user_id)->first();
        $user =  objectToArray($user);
        return response()->json(['code'=>0,'data'=>$user]);
    }
    
    public  function myTravel(Request $request){
        $type = $request->input('type',0);
        $user_id = $request->input('user_id',0);
        if ($type==1){
            //未出行
            $lists = DB::table('travel_plan')->where('user_id',$user_id)->where('success_status',1)->paginate(8);
            
        }
        if ($type==2){
            //已出行
            $lists = DB::table('travel_plan')->where('user_id',$user_id)->where('success_status',2)->paginate(8);
        }
        if ($type==3){
            //分享
            $lists = DB::table('share as s')
            ->leftJoin('travel_plan as tp','tp.id','=','s.plan_id')
            ->where('s.user_id',$user_id)
            ->orderBy('s.created_at','desc')
            ->paginate(8);
        }
        $lists =  objectToArray($lists);
        return response()->json(['code'=>0,'data'=>$lists]);
    }
}